<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Proposal Generation</title>
  <script type="text/javascript" src="arjs/v2.1.3/ar-js-core.js"></script>
  <script type="text/javascript" src="arjs/v2.1.3/ar-js-pdf.js"></script>
  <script type="text/javascript" src="arjs/v2.1.3/ar-js-html.js"></script>
  <script type="text/javascript">
    const ARJS = GC.ActiveReports.Core;
    const licenseKey = '';
    ARJS.setLicenseKey(licenseKey);
    ARJS.PageReport.LicenseKey = licenseKey;
    const fonts = [
      {
        name: '微软雅黑',
        source: 'static/fonts/Arial-Unicode.ttf',
      },
      {
        name: '微软雅黑',
        weight: 'bold',
        source: 'static/fonts/Arial-Unicode-Bold.ttf',
      },
      {
        name: 'Arial',
        weight: 'bold',
        style: 'italic',
        source: 'static/fonts/arialbi.ttf',
      },
      {
        name: 'Arial',
        style: 'italic',
        source: 'static/fonts/ariali.ttf',
      },
      {
        name: 'Arial',
        weight: 'bold',
        source: 'static/fonts/arialbd.ttf',
      },
      {
        name: 'Arial',
        source: 'static/fonts/arial.ttf',
      },
    ];
    ARJS.FontStore.registerFonts(fonts);
  </script>
  <script>
    const settings = {
      info: {
        title: 'Invoice List',
        subject: 'This is the Invoice List',
        author: 'John K',
        keywords: 'PDF; import; export',
      },
      fonts: fonts,
    };
    function blob2base64(blob) {
      // document.getElementById('pdf').src = URL.createObjectURL(blob)
      return new Promise((resolve, reject) => {
        var reader = new FileReader();
        reader.onloadend = () => {
          resolve(reader.result);
        };
        reader.onerror = () => {
          reject(reader.err);
        };
        reader.readAsDataURL(blob);
      });
    }

    async function generateProposal(mainReport, dsparam) {
      const start = new Date();
      const dataSource = JSON.parse(dsparam);
      const category = dataSource.para.reportCategory;
      console.debug(`start generate proposal inner ${mainReport}, puppeteer HTML ${start}`);
      const PDF = GC.ActiveReports.PdfExport;
      const pageReport = new ARJS.PageReport();
      try {
        await pageReport.load(mainReport);
        if ('LicenseError' === pageReport.name) {
          throw new Error('License Error');
        }
        if (pageReport.parameters.dsparam) {
          pageReport.parameters.dsparam.values = [dsparam];
        }
        const pageDocument = await pageReport.run();
        console.debug('page report randered completed, start export the PDF');
        const result = await PDF.exportDocument(pageDocument, settings, pageNum => {
          console.debug(`exporting PDF version at page ${pageNum}`);
        });
        console.debug('pdf document exported completed');
        return blob2base64(result.data);
      } catch (e) {
        console.error(`error occured while generate the proposal, ${e}`);
      }
    }

    const HTML_SETTING = { autoPrint: false, embedImages: 'embed', multiPage: false, outputType: 'html', title: '' };
    async function generateHtml(mainReport, dsparam) {
      const start = new Date();
      const dataSource = JSON.parse(dsparam);
      const category = dataSource.para.reportCategory;
      const HTML = GC.ActiveReports.HtmlExport;
      const pageReport = new ARJS.PageReport();
      return await pageReport
        .load(mainReport, {
          resourceLocator: {
            getResource: (uri, sourceContentType) => {
              if (uri.indexOf(category) < 0) {
                uri = category + '/' + uri;
              }
              const baseUrl = 'http://';
              if (uri.indexOf('templates/') >= 0) {
                uri = baseUrl + uri;
              } else {
                uri = baseUrl + 'templates/' + uri;
              }

              return new Promise((resolve, reject) => {
                function success() {
                  const data = JSON.parse(this.responseText);
                  resolve(data);
                }
                function error(err) {
                  console.log('Error Occurred :', err);
                  reject(err);
                }
                const xhr = new XMLHttpRequest();
                xhr.onload = success;
                xhr.onerror = error;
                xhr.open('GET', uri);
                xhr.send();
              });
            },
          },
        })
        .then(() => {
          if ('LicenseError' === pageReport.name) {
            throw new Error('License Error');
          }
          if (pageReport.parameters.dsparam) {
            pageReport.parameters.dsparam.values = [dsparam];
          }
        })
        .then(() => pageReport.run())
        .then(pageDocument => HTML.exportDocument(pageDocument, settings, pageNum => { }))
        .then(async result => {
          return result.data;
        });
    }
  </script>
</head>

<body>
  <embed id="pdf" type="application/pdf" width="100%" height="800px">
</body>

</html>